package com.simplecontact.services;

import java.io.IOException;
import java.util.Date;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.simplecontact.R;
import com.simplecontact.activities.ActCreateCalendar;
import com.simplecontact.classes.Calendar;
import com.simplecontact.classes.Calendar.CalendarColumns;
import com.simplecontact.classes.CalendarBundle;

public class SERAlarm extends Service{
	
	NotificationManager mNM;
	MediaPlayer mp ;
	int i;	
	
	public CalendarBundle prepareToEditCalendar(int id){
		CalendarBundle cb = null;
		Cursor c = getContentResolver().query(Calendar.CalendarColumns.CONTENT_URI, null, null, null, null);				
        if (c.moveToFirst()) {        	
			int ColumnId = c.getColumnIndex(Calendar.CalendarColumns._ID);						
			int columnDateTime = c.getColumnIndex(Calendar.CalendarColumns.DATETIME);
			int columnContent = c.getColumnIndex(Calendar.CalendarColumns.CONTENT);
			int columnUrlMusic = c.getColumnIndex(Calendar.CalendarColumns.URLMUSIC);			
			do {
				// Get the field values								
				if(c.getInt(ColumnId)==id){														
					cb = new CalendarBundle(id, c.getLong(columnDateTime),c.getString(columnContent),c.getString(columnUrlMusic));
					break;
				}
			} while (c.moveToNext());			
		}
        return cb;
	}
	
    @Override
    public void onCreate() {
    	        
    }
    
    @Override
    public void onDestroy() {
        // Cancel the notification -- we use the same ID that we had used to start it
        mNM.cancel(R.string.strAlarmServiceStarted);
        mp.stop();
        // Tell the user we stopped.
        Toast.makeText(this, R.string.strAlarmServiceFinished, Toast.LENGTH_SHORT).show();        
    }

    /**
     * The function that runs in our worker thread
     */
    Runnable mTask = new Runnable() {
        public void run() {
            // Normally we would do some work here...  for our sample, we will
            // just sleep for 30 seconds.
            long endTime = System.currentTimeMillis() + 15*1000;
            String s = getURLAlarmFromId(i);
            if(s=="" || s==null)
            {
            	mp = MediaPlayer.create(SERAlarm.this, R.raw.test_cbr);
            	mp.start();
            }
            else{
            	mp = new MediaPlayer();
                try {
					mp.setDataSource(s);
	                mp.prepare();
	                mp.start();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}            	
            }
            while (System.currentTimeMillis() < endTime) {
                synchronized (mBinder) {
                    try {
                        mBinder.wait(endTime - System.currentTimeMillis());                        
                    } catch (Exception e) {
                    }
                }
            }
            // Done with our work...  stop the service!
            SERAlarm.this.stopSelf();
        }
    };

    public String getURLAlarmFromId(int id){    	
    	Cursor c = getContentResolver().query(CalendarColumns.CONTENT_URI, new String[]{CalendarColumns.URLMUSIC}, CalendarColumns._ID + "=" + id, null, null);
		if(c.moveToFirst()){
			int Column = c.getColumnIndex(CalendarColumns.URLMUSIC);    					
			return c.getString(Column);
		}
    	return "";
    }
    
    public int getIdFromTime(long t){    	
    	Cursor c = getContentResolver().query(CalendarColumns.CONTENT_URI, new String[]{CalendarColumns._ID, CalendarColumns.DATETIME}, null, null, null);
		if(c.moveToFirst()){
			int Column = c.getColumnIndex(CalendarColumns._ID);
			int ColumnD = c.getColumnIndex(CalendarColumns.DATETIME);
			do{
				long r = c.getLong(ColumnD); 
				if(r==t){					
					return c.getInt(Column);
				}
			}while(c.moveToNext());			
		}
    	return -1;
    }
    
    public long getNow(){
    	java.util.Calendar c = java.util.Calendar.getInstance();
    	int y = c.get(java.util.Calendar.YEAR);
    	y-=1900;
    	int m = c.get(java.util.Calendar.MONTH);
    	int d = c.get(java.util.Calendar.DAY_OF_MONTH);
    	int h = c.get(java.util.Calendar.HOUR_OF_DAY);
    	int mi = c.get(java.util.Calendar.MINUTE);
    	long res = Date.parse(new Date(y, m, d, h, mi).toGMTString());
    	return res;
    }
    
    public int onStartCommand (Intent intent, int flags, int startId){    	    	
    	i = getIdFromTime(getNow());    	
    	mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);        
        showNotification();
        Thread thr = new Thread(null, mTask, "SERAlarm");
        thr.start();
    	return super.onStartCommand (intent, flags, startId);
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    private void showNotification() {
        // In this sample, we'll use the same text for the ticker and the expanded notification
        CharSequence text = getText(R.string.strAlarmServiceStarted);
                
        // Set the icon, scrolling text and timestamp
        Notification notification = new Notification(R.drawable.bell, text, System.currentTimeMillis());

        RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification_layout);
        contentView.setImageViewResource(R.id.image, R.drawable.clock_stop);
        contentView.setTextViewText(R.id.text, getString(R.string.strClickToOpenCalendar));        
        notification.contentView = contentView;
                                 
        // The PendingIntent to launch our activity if the user selects this notification        
        Intent k = new Intent(this, ActCreateCalendar.class);        
        k.putExtra("calendarbundle", prepareToEditCalendar(i));
        k.putExtra("ser", i);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, k, 0);
                
        // Set the info for the views that show in the notification panel.
        notification.contentIntent = contentIntent;  
        
        // Send the notification.
        // We use a layout id because it is a unique number.  We use it later to cancel.
        mNM.notify(R.string.strAlarmServiceStarted, notification);
    }    
	
    private final IBinder mBinder = new Binder() {
        @Override
		protected boolean onTransact(int code, Parcel data, Parcel reply,
		        int flags) throws RemoteException {
            return super.onTransact(code, data, reply, flags);
        }
    };
}
